package com.Test;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * Created by Administrator on 2016/4/25.
 */
@WebFilter(filterName = "PriviledgeFilter")
public class PriviledgeFilter implements Filter {
    private Log log = LogFactory.getLog(this.getClass());
    private Properties pp = new Properties(); //保存所有的权限
    private String message= "权限不足,请登录后操作！！！";
    public void destroy() {
        pp = null;
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request   = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session = request.getSession();
        //request对象
        String requestURI = request.getRequestURI().replace(request.getContextPath()+"/","");
        String action     = req.getParameter("action");
        action            = action == null ? "view" : action;
        String uri        = requestURI + "?action=" + action;
        String user       = (String) request.getSession(true).getAttribute("user");
        user              = user == null ?"guest" : user;
        boolean authentificated = false;
        log.info(pp.keySet());
        for(Object obj:pp.keySet()){
            String key = ((String) obj);
            log.info(uri+":"+user+":"+key);
            if(uri.matches(key.replace("?","\\?").replace(".","\\.").replace("*",".*"))){
                if(user.equals(pp.get(key))){
                    authentificated = true;
                    break;
                }
            }
        }
        log.info(authentificated);
        if(!authentificated){
            //throw new RuntimeException(new AccountException("您无权访问该页面,请登录后访问！！！"));
            session.setAttribute("message",message);
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {
        String file     = config.getInitParameter("file"); //初始化参数获取文件位置
        String realPath = config.getServletContext().getRealPath(file); //文件实际位置
        try {
            pp.load(new FileInputStream(realPath)); //加载所有的权限配置
        }catch (Exception e){
            config.getServletContext().log("读取权限控制文件失败。",e);
        }
    }

}
